import Router from 'koa-router';
import { pool } from '../../config/database';
import { authMiddleware } from '../../middleware/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { ApiResponse, Merchant, MerchantCreateInput, MerchantUpdateInput, JwtPayload } from '../../types';

const router = new Router({ prefix: '/api/merchants' });

// 获取商家列表
router.get('/', async (ctx) => {
  try {
    const { page = 1, limit = 10, status, type, search } = ctx.query;
    const offset = (Number(page) - 1) * Number(limit);
    
    let whereClause = 'WHERE 1=1';
    const params: any[] = [];
    
    if (status) {
      whereClause += ' AND status = ?';
      params.push(status);
    }
    
    if (type) {
      whereClause += ' AND type = ?';
      params.push(type);
    }
    
    if (search) {
      whereClause += ' AND (name LIKE ? OR location LIKE ?)';
      params.push(`%${search}%`, `%${search}%`);
    }
    
    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM merchants ${whereClause}`,
      params
    ) as [RowDataPacket[], any];
    const total = countResult[0].total;
    
    // 获取商家列表
    const [merchants] = await pool.execute(
      `SELECT * FROM merchants ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
      [...params, Number(limit), offset]
    ) as [RowDataPacket[], any];
    
    ctx.body = {
      success: true,
      data: merchants,
      meta: {
        total,
        page: Number(page),
        limit: Number(limit),
        totalPages: Math.ceil(total / Number(limit))
      }
    } as ApiResponse<Merchant[]>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取商家列表失败：' + error.message
    } as ApiResponse;
  }
});

// 获取商家详情
router.get('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    
    const [merchants] = await pool.execute(
      'SELECT * FROM merchants WHERE id = ?',
      [id]
    ) as [RowDataPacket[], any];
    
    if (merchants.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '商家不存在'
      } as ApiResponse;
      return;
    }
    
    const merchant = merchants[0] as Merchant;
    
    ctx.body = {
      success: true,
      data: merchant
    } as ApiResponse<Merchant>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取商家详情失败：' + error.message
    } as ApiResponse;
  }
});

// 创建商家（需要认证）
router.post('/', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const {
      name,
      type = 'basic',
      location,
      established,
      specialties,
      logo,
      description,
      certification,
      commission = 0.05
    } = ctx.request.body as MerchantCreateInput;
    
    if (!name) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '商家名称不能为空'
      } as ApiResponse;
      return;
    }
    
    // 检查用户是否已经是商家
    const [existingMerchants] = await pool.execute(
      'SELECT id FROM merchants WHERE user_id = ?',
      [user.id]
    ) as [RowDataPacket[], any];
    
    if (existingMerchants.length > 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '您已经是商家，无法重复创建'
      } as ApiResponse;
      return;
    }
    
    // 检查商家名称是否已存在
    const [existingNames] = await pool.execute(
      'SELECT id FROM merchants WHERE name = ?',
      [name]
    ) as [RowDataPacket[], any];
    
    if (existingNames.length > 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '商家名称已存在'
      } as ApiResponse;
      return;
    }
    
    // 创建商家
    const [result] = await pool.execute(
      `INSERT INTO merchants (name, type, location, established, specialties, logo, description, certification, commission, user_id) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        name,
        type,
        location || null,
        established || null,
        specialties ? JSON.stringify(specialties) : null,
        logo || null,
        description || null,
        certification ? JSON.stringify(certification) : null,
        commission,
        user.id
      ]
    ) as [ResultSetHeader, any];
    
    // 获取创建的商家信息
    const [merchants] = await pool.execute(
      'SELECT * FROM merchants WHERE id = ?',
      [result.insertId]
    ) as [RowDataPacket[], any];
    
    const merchant = merchants[0] as Merchant;
    
    ctx.body = {
      success: true,
      data: merchant,
      message: '商家创建成功'
    } as ApiResponse<Merchant>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '创建商家失败：' + error.message
    } as ApiResponse;
  }
});

// 更新商家信息
router.put('/:id', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    const updateData = ctx.request.body as MerchantUpdateInput;
    
    // 检查商家是否存在
    const [merchants] = await pool.execute(
      'SELECT * FROM merchants WHERE id = ?',
      [id]
    ) as [RowDataPacket[], any];
    
    if (merchants.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '商家不存在'
      } as ApiResponse;
      return;
    }
    
    const merchant = merchants[0] as Merchant;
    
    // 检查权限（只有商家自己或管理员可以修改）
    if (merchant.user_id !== user.id && user.email !== 'admin@example.com') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限修改此商家信息'
      } as ApiResponse;
      return;
    }
    
    // 构建更新字段
    const updateFields: string[] = [];
    const updateValues: any[] = [];
    
    Object.entries(updateData).forEach(([key, value]) => {
      if (value !== undefined) {
        if (key === 'specialties' || key === 'certification') {
          updateFields.push(`${key} = ?`);
          updateValues.push(JSON.stringify(value));
        } else {
          updateFields.push(`${key} = ?`);
          updateValues.push(value);
        }
      }
    });
    
    if (updateFields.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '没有要更新的字段'
      } as ApiResponse;
      return;
    }
    
    updateValues.push(id);
    
    // 更新商家信息
    await pool.execute(
      `UPDATE merchants SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
      updateValues
    );
    
    // 获取更新后的商家信息
    const [updatedMerchants] = await pool.execute(
      'SELECT * FROM merchants WHERE id = ?',
      [id]
    ) as [RowDataPacket[], any];
    
    const updatedMerchant = updatedMerchants[0] as Merchant;
    
    ctx.body = {
      success: true,
      data: updatedMerchant,
      message: '商家信息更新成功'
    } as ApiResponse<Merchant>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '更新商家信息失败：' + error.message
    } as ApiResponse;
  }
});

// 删除商家
router.delete('/:id', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    
    // 检查商家是否存在
    const [merchants] = await pool.execute(
      'SELECT * FROM merchants WHERE id = ?',
      [id]
    ) as [RowDataPacket[], any];
    
    if (merchants.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '商家不存在'
      } as ApiResponse;
      return;
    }
    
    const merchant = merchants[0] as Merchant;
    
    // 检查权限（只有商家自己或管理员可以删除）
    if (merchant.user_id !== user.id && user.email !== 'admin@example.com') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限删除此商家'
      } as ApiResponse;
      return;
    }
    
    // 检查是否有关联的配置和订单
    const [configs] = await pool.execute(
      'SELECT COUNT(*) as count FROM computer_configs WHERE merchant_id = ?',
      [id]
    ) as [RowDataPacket[], any];
    
    const [orders] = await pool.execute(
      'SELECT COUNT(*) as count FROM orders WHERE merchant_id = ?',
      [id]
    ) as [RowDataPacket[], any];
    
    if (configs[0].count > 0 || orders[0].count > 0) {
      // 软删除：将状态设为inactive
      await pool.execute(
        'UPDATE merchants SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
        ['inactive', id]
      );
      
      ctx.body = {
        success: true,
        message: '商家已停用（因为存在关联的配置或订单）'
      } as ApiResponse;
    } else {
      // 硬删除
      await pool.execute('DELETE FROM merchants WHERE id = ?', [id]);
      
      ctx.body = {
        success: true,
        message: '商家删除成功'
      } as ApiResponse;
    }
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '删除商家失败：' + error.message
    } as ApiResponse;
  }
});

export default router; 